// 响应状态码常量
const RESPONSE_CODES = {
  SUCCESS: 200,              // 成功
  CREATED: 201,              // 创建成功
  BAD_REQUEST: 400,          // 请求参数错误
  UNAUTHORIZED: 401,         // 未授权
  FORBIDDEN: 403,            // 禁止访问
  NOT_FOUND: 404,            // 资源不存在
  CONFLICT: 409,             // 冲突（如用户已存在）
  VALIDATION_ERROR: 422,     // 验证错误
  SERVER_ERROR: 500,         // 服务器内部错误
};

// 统一响应格式化函数
const formatResponse = (code, success, message, data = null, error = null) => {
  const response = {
    code,
    success,
    message
  };

  if (data !== null) {
    response.data = data;
  }

  if (error !== null) {
    response.error = error;
  }

  return response;
};

// 成功响应
const successResponse = (res, message = '操作成功', data = null, code = RESPONSE_CODES.SUCCESS) => {
  return res.status(200).json(formatResponse(code, true, message, data));
};

// 创建成功响应
const createdResponse = (res, message = '创建成功', data = null) => {
  return res.status(201).json(formatResponse(RESPONSE_CODES.CREATED, true, message, data));
};

// 错误响应
const errorResponse = (res, message = '操作失败', code = RESPONSE_CODES.SERVER_ERROR, error = null, httpStatus = 500) => {
  return res.status(httpStatus).json(formatResponse(code, false, message, null, error));
};

// 400错误响应
const badRequestResponse = (res, message = '请求参数错误', error = null) => {
  return res.status(400).json(formatResponse(RESPONSE_CODES.BAD_REQUEST, false, message, null, error));
};

// 401错误响应
const unauthorizedResponse = (res, message = '未授权访问', error = null) => {
  return res.status(401).json(formatResponse(RESPONSE_CODES.UNAUTHORIZED, false, message, null, error));
};

// 404错误响应
const notFoundResponse = (res, message = '资源不存在', error = null) => {
  return res.status(404).json(formatResponse(RESPONSE_CODES.NOT_FOUND, false, message, null, error));
};

// 409冲突响应
const conflictResponse = (res, message = '资源冲突', error = null) => {
  return res.status(400).json(formatResponse(RESPONSE_CODES.CONFLICT, false, message, null, error));
};

module.exports = {
  RESPONSE_CODES,
  formatResponse,
  successResponse,
  createdResponse,
  errorResponse,
  badRequestResponse,
  unauthorizedResponse,
  notFoundResponse,
  conflictResponse
};